<template>
	<div class="system-edit-menu-container">
		<el-dialog :title="(acType === 'add' ? '新增' : '修改') + '菜单'" v-model="isShowDialog" width="769px"
			:close-on-click-modal="false">
			<el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" size="default" label-width="80px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="菜单类型" prop="menuType">
							<el-radio-group v-model="ruleForm.menuType">
								<el-radio label="M">目录</el-radio>
								<el-radio label="C" v-if="ruleForm.parentId">菜单</el-radio>
								<el-radio label="F" v-if="ruleForm.parentId">按钮</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="菜单名称" prop="menuName">
							<el-input v-model="ruleForm.menuName" placeholder="请填写菜单名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="菜单编码" prop="menuCode">
							<el-input v-model="ruleForm.menuCode" placeholder="请填写菜单编码" clearable></el-input>
						</el-form-item>
					</el-col>
					<template v-if="ruleForm.menuType !== 'F'">

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="路由路径" prop="path">
								<el-input v-model="ruleForm.path" placeholder="路由中的 path 值" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="菜单图标" prop="icon">
								<IconSelector placeholder="请选择菜单图标" v-model="ruleForm.icon" />
							</el-form-item>
						</el-col>
					</template>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="备注信息">
							<el-input v-model="ruleForm.remark" placeholder="请填写备注信息" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="菜单排序">
							<el-input-number v-model="ruleForm.orderNum" :min="0" controls-position="right"
								placeholder="请输入排序" class="w100" />
						</el-form-item>
					</el-col>
					<el-col v-if="ruleForm.menuType !== 'M'" :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="接口配置">
							<el-input v-model="urlNames" style="width: 600px" placeholder="请配置接口" @focus="focusUrl"
								@click="focusUrl" />
							<!-- <el-select v-model="urlNames" multiple clearable collapse-tags placeholder="请配置接口"
								popper-class="custom-header" :max-collapse-tags="10" style="width: 600px" @focus="focusUrl"  >
							</el-select> -->
						</el-form-item>
					</el-col>
					<template v-if="ruleForm.menuType !== 'F'">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="是否隐藏">
								<el-radio-group v-model="ruleForm.visible">
									<el-radio v-for="dict in visibleOptions" :key="dict.value" :label="dict.value">{{
										dict.label }}</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="菜单状态">
								<el-radio-group v-model="ruleForm.status">
									<el-radio v-for="dict in statusOptions" :key="dict.value" :label="dict.value">{{
										dict.label }}</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>

					</template>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default" :loading="loading">{{ acType === 'add' ?
						'新增' : '修 改' }}</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog title="接口配置" v-model="isShowDialogUrl" width="650px">
			<el-table :data="menuUrlList" ref="multipleTableRef" style="width: 100%" :max-height="600" row-key="urlCode"
				@select="handleSelectionChange">
				<el-table-column fixed type="selection" width="55" align="center" reserve-selection />
				<el-table-column label="接口名称" prop="urlName" show-overflow-tooltip min-width="200"></el-table-column>
				<el-table-column label="菜单地址" prop="paths" show-overflow-tooltip min-width="200"></el-table-column>
			</el-table>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { reactive, toRefs, defineComponent, ref, unref, getCurrentInstance, nextTick } from 'vue';
import IconSelector from '@/components/iconSelector/index.vue';
import { addMenuApi, editMenuApi, getMenuApi } from "@/api/auth/menu/index";
import { useUserStoreHook } from "@/store/modules/user"
import { ElMessage } from "element-plus"
export default defineComponent({
	name: 'systemEditMenu',
	components: { IconSelector },
	props: {
		acType: {
			type: String,
			default: () => 'add'
		},
		menuUrlList: {
			type: Array,
			default: () => []
		}
	},
	setup(props, { emit }) {
		const ruleFormRef = ref<HTMLElement | null>(null);
		const { proxy } = getCurrentInstance() as any;
		const state = reactive({
			loading: false,
			isShowDialog: false,
			isShowDialogUrl: false,
			urls: [],
			urlNames: [],
			visibleOptions: [{
				label: '显示',
				value: 0
			}, {
				label: '隐藏',
				value: 1
			}
			],
			statusOptions: [{
				label: '正常',
				value: 0
			}, {
				label: '停用',
				value: 1
			}
			],
			// 参数请参考 `/src/router/route.ts` 中的 `dynamicRoutes` 路由菜单格式
			ruleForm: {
				menuId: undefined,//菜单id
				menuCode: '',	//菜单编码·
				menuName: '', // 菜单名称
				parentId: null, // 上级菜单Id
				orderNum: null,	//显示顺序
				path: '',	//路由地址
				menuType: 'M', // 菜单类型
				visible: 0, // 是否隐藏
				status: 0,	//菜单状态
				icon: '',	//图标名称
				remark: ''	//备注
			},
			// 表单校验
			rules: {
				path: [
					{ required: true, message: "路由地址不能为空", trigger: "blur" },
				],
				menuName: [
					{ required: true, message: "菜单名称不能为空", trigger: "blur" },
				],
				menuType: [
					{ required: true, message: "菜单类型不能为空", trigger: "blur" },
				],
				menuCode: [
					{ required: true, message: "菜单编码不能为空", trigger: "blur" },
				],
				icon: [
					{ required: true, message: "图标名称不能为空", trigger: "blur" },
				],
			},
			menuData: [], // 上级菜单数据
		});

		// 打开弹窗
		const openDialog = (row: any) => {
			state.loading = true;
			initForm();

			nextTick(async () => {
				console.log(11111);

				if (props.acType == 'add') {
					if (row?.menuId) {
						state.ruleForm.parentId = row.menuId
						state.ruleForm.menuCode = row.menuCode
					}
				} else {
					let res = await getMenuApi({ id: row.menuId })
					if (res?.data) {
						state.ruleForm = res.data
						state.urls = res.data?.urls
						if (state.urls.length > 0) {
							props.menuUrlList.forEach(item => {
							if (state.urls.includes(item.urlCode)) state.urlNames.push(item.urlName)
						})
						}
						
					}
				}
				state.isShowDialog = true;
				state.loading = false;
			})
		};

		// 关闭弹窗
		const closeDialog = () => {
			state.isShowDialog = false;
		};
		// 取消
		const onCancel = () => {
			closeDialog();
		};
		// 新增
		const onSubmit = () => {
			console.log(state.ruleForm);

			const formWrap = unref(ruleFormRef) as any;
			if (!formWrap) return;
			formWrap.validate((valid: boolean) => {
				if (valid) {
					state.loading = true;
					let formData = {
						menu: state.ruleForm,
						urls: state.ruleForm.menuType != 'M' ? state.urls : []
					}
					if (props.acType === 'add') {
						//添加
						addMenuApi(formData).then(() => {
							ElMessage.success('菜单添加成功');
							closeDialog(); // 关闭弹窗
							resetMenuSession()
							emit('menuList')
						}).finally(() => {
							state.loading = false;
						})
					} else {
						//修改
						editMenuApi(formData).then(() => {
							ElMessage.success('菜单修改成功');
							closeDialog(); // 关闭弹窗
							resetMenuSession()
							emit('menuList')
						}).finally(() => {
							state.loading = false;
						})
					}
				}
			})
		};
		// 重置菜单session
		const resetMenuSession = () => {
			if (state.ruleForm.menuType == 'F') return
			const userStore = useUserStoreHook()
			userStore.changeRouter()
		};
		const initForm = () => {
			state.ruleForm = {
				menuId: undefined,//菜单id
				menuCode: '',	//菜单编码·
				menuName: '', // 菜单名称
				parentId: null, // 上级菜单Id
				orderNum: null,	//显示顺序
				path: '',	//路由地址
				menuType: 'M', // 菜单类型
				visible: 0, // 是否隐藏
				status: 0,	//菜单状态
				icon: '',	//图标名称
				remark: ''	//备注	
			}
			state.urls = []
			state.urlNames = []
		};
		// 打开接口配置弹出
		const focusUrl = () => {
			if (state.isShowDialogUrl) return
			state.isShowDialogUrl = true
			nextTick(() => {
				setDefaultSelection()
			})
		}
		// 选择url
		const handleSelectionChange = (arr) => {
			console.log('选择数据改变');
			state.urls = []
			state.urlNames = []
			arr.forEach(item => {
				state.urls.push(item.urlCode)
				state.urlNames.push(item.urlName)
			});

		}
		const multipleTableRef = ref(null);
		// 设置默认选择
		const setDefaultSelection = () => {
			if (multipleTableRef.value) {
				// 先清空选择
				multipleTableRef.value.clearSelection();
				// 设置默认选中项
				props.menuUrlList.forEach(row => {
					if (state.urls.includes(row.urlCode)) {
						nextTick(() => {
							multipleTableRef.value.toggleRowSelection(row, true);

						});
					}
				});
			}
		};

		return {
			ruleFormRef,
			multipleTableRef,
			openDialog,
			closeDialog,
			onCancel,
			onSubmit,
			focusUrl,
			resetMenuSession,
			handleSelectionChange,
			...toRefs(state),
		};
	},
});
</script>
